import React from "react";
import { useAppSelector } from "../store";
import { Navigate } from "react-router-dom";
const Home = React.lazy(() => import("../views/home"));
const City = React.lazy(() => import("../views/city"));
const Login = React.lazy(() => import("../views/login"));
const Detail = React.lazy(() => import("../views/detail"));
const MainLayout = React.lazy(() => import("../mainLayout"));
const Car = React.lazy(() => import("../views/car"));
const Search = React.lazy(() => import("../views/search"));

export interface RouteType {
  path: string;
  element: JSX.Element;
  children?: RouteType[];
}

// 私有路由： 要去登录 
const PrivateRouter: React.FC<{ children: JSX.Element }> = ({ children }) => {
	// 获取仓库 token
  const token = useAppSelector((state) => state.user.token);
	// 没有登录
  if (!token) {
		// 去登录页面
    return <Navigate to="/login"></Navigate>;
  }
	// 正常访问
  return children;
};

export const routes: RouteType[] = [
  {
    path: "/",
    element: <MainLayout></MainLayout>,
    children: [
      {
        path: "/",
        element: <Home></Home>,
      },
      {
        path: "/city",
        element: <City></City>,
      },
      {
        path: "/car",
        element: (
          <PrivateRouter>
            <Car></Car>
          </PrivateRouter>
        ),
      },
    ],
  },
  {
    path: "/login",
    element: <Login></Login>,
  },
  {
    path: "/detail/:id",
    element: <Detail></Detail>,
  },
  {
    path: "/search",
    element: <Search></Search>,
  },
];
